<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/5/7
 * Time: 10:51
 */

namespace app\api\service;


use app\api\controller\BaseCotroller;
use app\api\model\Product as ProductModel;
use app\api\model\Image as ImageModel;
use app\api\validate\IDMustBePostiveInt;
use app\api\validate\PagingParameter;
use app\api\validate\ProductNew;
use app\lib\exception\ParameterException;
use app\lib\exception\ProductException;
use app\lib\exception\SuccessMessage;
use think\Db;
use think\Exception;

class Product extends BaseCotroller
{
    //前置操作-用户权限验证
    protected $beforeActionList = [
        'checkPrimaryScope' => [
            'only' => 'getProductsByPage,createOrUpdateProduct,deleteProductByID'
        ]
    ];

    /*
     * cms 获取商品信息列表 -分页获取
     * @url /product/all
     * @GET
     * @params: $page int 第几页
     *          $size int 每页条数
     * return array
     * */
    public function getProductsByPage($page = 1, $size = 20){
        $product = new ProductModel();
        $count = $product->count();
        $paginProducts = $product::getSummaryByPage($page, $size);
        if ($paginProducts->isEmpty()){
            return [
                'data' => [],
                'current_page' => $paginProducts->getCurrentPage()
            ];
        }
        return [
            'data' => $paginProducts,
            'count' => $count
        ];
    }

    /*
     * cms 商品添加或者更新
     * @url /product
     * @POST
     * return 更新成功
     * */
    public function createOrUpdateProduct($dataArray){
        $validata = new ProductNew();
        $validata->goCheck();

        $product = new ProductModel();
        if (array_key_exists('id', $dataArray) && !empty($dataArray['id'])) {
            $product->save($dataArray, ['id' => $dataArray['id']]);
        } else {
            $product->save($dataArray);
        }
        return $product;
    }

    /*
     * cms 给商品添加主图片
     * @url /prodct/main_img
     * @POST
     * @id 商品id
     * */
    public function addProductImgByID($id, $image){
        $dataArray = [];
        $imgInfo = $this->getUploadImageName($image, 1);
        if (!$imgInfo) {
            throw new ParameterException([
                'msg' => '上传文件不能为空'
            ]);
        }

        Db::startTrans();
        try{
            $image = new ImageModel();
            $image->save($imgInfo);

            $dataArray['main_img_url'] = $imgInfo['url'];
            $dataArray['from'] = $imgInfo['from'];
            $dataArray['img_id'] = $image->id;

            $product = new ProductModel();
            $product = $product->get($id);
            if (!$product){
                throw new ProductException();
            }
            $product->save($dataArray);
            Db::commit();

            return [
                'main_img_url' => $product['main_img_url']
            ];
        }catch (Exception $e){
            Db::rollback();
            throw $e;
        }
    }

    /*
     * 删除商品 软删除
     * @delete @url /product
     * @id 商品id
     * */
    public function deleteProductByID($id){
        ProductModel::destroy($id);
        return new SuccessMessage();
    }

    // 把上传图片移动到images文件夹，返回上传图片的名称
    public function getUploadImageName($img, $from){
//        $fileImg = $_FILES['image'];
        $file = request()->file($img);
        if($file){
            $info = $file->validate(['size'=>1567899,'ext'=>'jpg,png,gif'])
                ->move(ROOT_PATH . 'public' . DS . 'images', '');
            if($info){
                $infomsg = $info->getSaveName();
                return [
                    'url' => '/' . $infomsg,
                    'from' => $from
                ];
            }else{
                return $file->getError();
            }
        }else{
            throw new ParameterException([
                'msg' => '上传的文件为空'
            ]);
        }
    }
}